package com.etb.wisdom.eframe.org.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.etb.core.pojo.CriteriaType;
import com.etb.core.service.ETBService;
import com.etb.core.utils.DataUtil;
import com.etb.core.utils.EncryptionUtil;
import com.etb.wisdom.eframe.auth.AuthConstant.AuthType;
import com.etb.wisdom.eframe.auth.AuthConstant.PartyType;
import com.etb.wisdom.eframe.model.EtbPartyAuth;
import com.etb.wisdom.eframe.model.EtbUser;
import com.etb.wisdom.eframe.model.OrgEmployee;
import com.etb.wisdom.eframe.org.service.OrgEmployeeService;
import com.etb.wisdom.eframe.system.constant.SecurityConstant;

@Service
public class OrgEmployeeServiceImpl extends ETBService implements OrgEmployeeService {
	
	@Override
	public List queryAll(String... args) {
		//TODO 添加数据权限
		return service.queryAll(OrgEmployee.class, args);
	}
	
	@Override
	public List<OrgEmployee> queryAllFromOrg() {
		CriteriaType criteria = new CriteriaType(OrgEmployee.class);
		criteria.addExpr("positionid_isnull", null);
		return service.query(criteria);
	}

	@Override
	public List<OrgEmployee> queryAllFromPosi() {
		CriteriaType criteria = new CriteriaType(OrgEmployee.class);
		criteria.addExpr("positionid_isnotnull", null);
		return service.query(criteria);
	}
	
	@Override
	public void save(OrgEmployee emp, String newPassword) {
		if(emp.getId() == null) {
			if(StringUtils.isBlank(emp.getPassword())) {
				emp.setPassword(EncryptionUtil.encrypt(SecurityConstant.DEFAULT_PASSWORD));
			} else {
				emp.setPassword(EncryptionUtil.encrypt(emp.getPassword()));
			}
		}
		if(StringUtils.isNotBlank(newPassword)) {
			emp.setPassword(EncryptionUtil.encrypt(newPassword));
		}
		service.save(emp);
		
		EtbUser user = new EtbUser();
		user.setLoginname(emp.getUserid());
		service.extend(user);
		user.setUsername(emp.getEmpname());
		user.setPassword(emp.getPassword());
		service.save(user);
	}
	
	@Override
	public void saveRole(String empId, String addRoleIds, String delRoleIds) {
		List<String> addIdList = DataUtil.split(addRoleIds);
		List<String> delIdList = DataUtil.split(delRoleIds);
		for(String id: addIdList) {
			EtbPartyAuth auth = new EtbPartyAuth();
			auth.setPartyid(empId);
			auth.setPartytype(PartyType.employee.toString());
			auth.setAuthid(id);
			auth.setAuthtype(AuthType.role.toString());
			service.save(auth);
		}
		for(String id: delIdList) {
			EtbPartyAuth auth = new EtbPartyAuth();
			auth.setPartyid(empId);
			auth.setPartytype(PartyType.employee.toString());
			auth.setAuthid(id);
			auth.setAuthtype(AuthType.role.toString());
			service.delete(auth);
		}
	}

}
